package com.eastcom.groovy.task.taskdirector.temp

import java.awt.TexturePaintContext.Int;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.InetAddress.Cache;
import java.sql.Date;
import java.sql.PreparedStatement
import java.sql.SQLException
import java.sql.Timestamp
import java.sql.Types;
import java.text.SimpleDateFormat
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.eastcom.groovy.tools.common.JmsJndiConfig
import com.eastcom.groovy.tools.common.MQCommunication
import com.eastcom.groovy.tools.common.ShellExecutor;
import com.eastcom.groovy.tools.db.DbEngine
import com.eastcom.groovy.tools.file.FileUtils;
import com.eastcom.groovy.tools.file.FtpUtils;
import com.eastcom.groovy.provider.*
import com.eastcom.groovy.tools.mail.*
import com.sun.java.util.jar.pack.Instruction.Switch;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.sun.org.apache.bcel.internal.util.ClassPath.Dir;

import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTPFile
import org.apache.commons.net.ftp.FTPFileFilter
import org.apache.tools.ant.types.FileList;
import org.springframework.dao.DataAccessException
import org.springframework.jdbc.core.support.AbstractLobCreatingPreparedStatementCallback
import org.springframework.jdbc.support.lob.LobCreator
import org.springframework.jdbc.support.lob.OracleLobHandler
import org.springframework.jdbc.support.nativejdbc.CommonsDbcpNativeJdbcExtractor
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
/**
 * 任务类，可配置
 * @author yuanyue
 *
 */
//CMCC-ADSL|QQ大乐斗|0|0|1|1|2|2|3|3|4|4|5|5|6|6|7|7|8|8|9|9|10|10|11|11|12|12|13|13|14|14|15|15|16|16|17|17|18|18|19|19|20|20|21|21|22|22|23|23
//CMCC-ADSL|QQ飞车|0|0|1|1|2|2|3|3|4|4|5|5|6|6|7|7|8|8|9|9|10|10|11|11|12|12|13|13|14|14|15|15|16|16|17|17|18|18|19|19|20|20|21|21|22|22|23|23
//CMCC-ADSL|反恐精英|0|0|1|1|2|2|3|3|4|4|5|5|6|6|7|7|8|8|9|9|10|10|11|11|12|12|13|13|14|14|15|15|16|16|17|17|18|18|19|19|20|20|21|21|22|22|23|23
//CMCC-ADSL|地下城与勇士|0|0|1|1|2|2|3|3|4|4|5|5|6|6|7|7|8|8|9|9|10|10|11|11|12|12|13|13|14|14|15|15|16|16|17|17|18|18|19|19|20|20|21|21|22|22|23|23
//CMCC-ADSL|大话水浒|0|0|1|1|2|2|3|3|4|4|5|5|6|6|7|7|8|8|9|9|10|10|11|11|12|12|13|13|14|14|15|15|16|16|17|17|18|18|19|19|20|20|21|21|22|22|23|23
//CMCC-ADSL|幻想三国|0|0|1|1|2|2|3|3|4|4|5|5|6|6|7|7|8|8|9|9|10|10|11|11|12|12|13|13|14|14|15|15|16|16|17|17|18|18|19|19|20|20|21|21|22|22|23|23
//CMCC-ADSL|战地之王|0|0|1|1|2|2|3|3|4|4|5|5|6|6|7|7|8|8|9|9|10|10|11|11|12|12|13|13|14|14|15|15|16|16|17|17|18|18|19|19|20|20|21|21|22|22|23|23
//CMCC-ADSL|手机QQ游戏|0|0|1|1|2|2|3|3|4|4|5|5|6|6|7|7|8|8|9|9|10|10|11|11|12|12|13|13|14|14|15|15|16|16|17|17|18|18|19|19|20|20|21|21|22|22|23|23
//CMCC-ADSL|英雄联盟|0|0|1|1|2|2|3|3|4|4|5|5|6|6|7|7|8|8|9|9|10|10|11|11|12|12|13|13|14|14|15|15|16|16|17|17|18|18|19|19|20|20|21|21|22|22|23|23
//CMCC-ADSL|穿越火线|0|0|1|1|2|2|3|3|4|4|5|5|6|6|7|7|8|8|9|9|10|10|11|11|12|12|13|13|14|14|15|15|16|16|17|17|18|18|19|19|20|20|21|21|22|22|23|23
class SimpleTxtFileTaskDirector_Game_BoCe_Top10_Day {
	/************************配置属性，可以修改，请尽量使用英文防止中文编码问题***************************/
	final String[] ftpLocalPath =  ["/export/home/zjcache","/export/home/ipnet/stope/data/zjcache_back"]
	final String ftpFileNameRegex ="TOP20GameBoCe(\\d+).txt"
	//没有时间的话用[]
	final String fileNameTimeFormat ="yyyyMMdd"
	final String timeFormat = "yyyyMMdd"
	final long fileLimit = 7200000
	final String dstdbBean = "oracle_132_ipnet"
	final int parseLineNumOnce = 1
	final String delimiter = "\\s*\\|\\s*"
	final String encode = "GB2312"
	static String insertSql = "insert into FLOW_GAME_TOP20_BOCE_DAY(ALL) values(?)"
	/***************************可配置部分结束***********************************************/

















	static ThreadPoolTaskExecutor threadPoolTaskExecutor
	static List<String> dstFieldList = new ArrayList()
	static List<Integer> dstFieldTypeList = new ArrayList()
	static int[] sqlTypes
	List<List<String>> parseResultList = new ArrayList()
	static Log logger = LogFactory.getLog(SimpleTxtFileTaskDirector_Game_BoCe_Top10_Day.class)



	/*********************initJob和doJob是要被程序调用的方法**************************/
	public boolean initJob(String jobId){
		insertSql = DbEngine.doDbInit(dstdbBean, dstFieldList, dstFieldTypeList, insertSql, true)
		sqlTypes = new int[dstFieldTypeList.size()]
		for(int i = 0; i < dstFieldTypeList.size(); i++){
			sqlTypes[i] = dstFieldTypeList.get(i)
		}
		println sqlTypes
		println insertSql
	}

	public boolean doJob(String jobId){
		doParseFile()
	}

	private doDbInit(){
		try{
			String reg = "\\w+\\s+\\w+([^\\(\\),]+)\\s*\\(([^\\)]+)"
			String dstTb
			String dstFields
			Pattern pattern = Pattern.compile(reg)
			Matcher matcher = pattern.matcher(insertSql)
			if(matcher.find()){
				dstTb = matcher.group(1)
				dstFields = matcher.group(2)
			}
			DbEngine.loadDb(dstdbBean, dstTb, dstFields, dstFieldList, dstFieldTypeList, true)
			sqlTypes = new int[dstFieldTypeList.size()]
			for(int i = 0; i < dstFieldTypeList.size(); i++){
				sqlTypes[i] = dstFieldTypeList.get(i)
			}
		}catch(Exception e){
			e.printStackTrace()
			logger.error(e.getMessage())
		}
	}
	private boolean doParseFile(){
			ftpLocalPath.each {
				try{
					Calendar fileTime = Calendar.getInstance();
					Calendar fileLimitTime = Calendar.getInstance();
					fileLimitTime.setTimeInMillis(new java.util.Date().getTime() - fileLimit);
				File dirs = new File(ftpLocalPath)
				File[] dirFile = dirs.listFiles(new FilenameFilter() {

					@Override
					public boolean accept(File dir, String name) {
						// TODO 自动生成的方法存根
						if(name.matches(ftpFileNameRegex)){
							return true;
						}
						return false;
					}
				});
				for(File f: dirFile){
					long time = f.lastModified();
					fileTime.setTimeInMillis(time);
					if(fileTime.before(fileLimitTime)){
						continue;
					}
					String fileNameTime = null;

					Pattern pat = Pattern.compile(ftpFileNameRegex)
					Matcher mat = pat.matcher(f.getName())
					boolean rs = mat.find()
					if(rs){
						fileNameTime = mat.group(1)
					}else{
						continue
					}
					BufferedReader reader = null;

					try {
						reader = new BufferedReader(new InputStreamReader(new FileInputStream(f), encode));
					} catch (Exception e) {
						e.printStackTrace()
					}
					StringBuilder context = new StringBuilder();
					String line = null;
					boolean isFileEnd = false;
					int counts = 0
					while(!isFileEnd){
						if(parseResultList.size() >= 15000){
							doInsertResult()
						}
						for(int i = 0; i < parseLineNumOnce; i++){
							try {
								line = reader.readLine()
								logger.debug("line="+line)
								if(line == null){
									isFileEnd = true
									break
								}
							} catch (Exception e) {
								e.printStackTrace()
							}
							context.append(line)
						}
						String parseContext = context.toString()
						List<String> valueList = contextParse(fileNameTime,parseContext)
						if(!(valueList == null)){
							parseResultList.add(valueList)
						}
						context = new StringBuilder();
						if(isFileEnd){
							logger.debug("文件已经读完！");
							doInsertResult()
							break;
						}
					}
				}
			}catch(Exception e){
				e.printStackTrace()
				logger.error(e.getMessage())
			}
		}

	}

	private List<String> contextParse(String param,String context){
		List<String> valueList =  new ArrayList();
		if(context == null || context.equals("")||context.equals("\\n")){
			return null
		}
		String[] record = context.split(delimiter)
		if(record == null || record.length < 1){
			return null
		}
		record.each {
			valueList.add(it)
			println it
		}
		return valueList
	}

	private boolean doInsertResult(){
		try{
			DbEngine dbEngine = SpringContextProvider.getBean("dbEngine")
			dbEngine.getJdbcUtil().setDataSource(DynamicBeanDomianProvider.getBean(dstdbBean))
			for(List<String> raw: parseResultList){
				Object[] param = new Object[raw.size()]
				println raw.size()
				for(int i = 0; i < raw.size(); i++){
					print raw.get(i)+"--"+sqlTypes[i]+"\t"
					try {
						switch(sqlTypes[i]){
							case Types.INTEGER:
							param[i] = Integer.valueOf(raw.get(i))
							break
							case Types.FLOAT:
							case Types.DOUBLE:
							param[i] = Double.valueOf(raw.get(i))
							break
							case Types.DECIMAL:
							case Types.NUMERIC:
							param[i] = BigDecimal.valueOf(Double.valueOf(raw.get(i)))
							break
							case Types.TIMESTAMP:
							java.util.Date date = new SimpleDateFormat(timeFormat).parse(raw.get(i))
							logger.debug(date)
							param[i] = new Timestamp(date.getTime())
							break
							case Types.DATE:
							java.util.Date date = new SimpleDateFormat(timeFormat).parse(raw.get(i))
							logger.debug(date)
							param[i] = new Date(date.getTime())
							break
							case Types.VARCHAR:
							case Types.NVARCHAR:
							param[i] = raw.get(i)
							break
							case Types.OTHER:
							param[i] = raw.get(i)
							break;
							default:
							param[i] = null
							logger.warn("入库数据库字段无法识别！使用Null插入！")
							break;
						}
					} catch (Exception e) {
						e.printStackTrace()
						logger.error(e.getMessage())
						param[i]=null
					}
				}
				try{
					dbEngine.getJdbcUtil().update(insertSql, param, sqlTypes)
				}catch(Exception e){
					e.printStackTrace()
					logger.error(e.getMessage())
				}
				println ""
			}
			parseResultList.clear()
		}catch(Exception e){
			e.printStackTrace()
			logger.error(e.getMessage())
		}
	}

}